from django.db import models

from common.utils import make_sha256_digest

FINANCING_STAGE_OPTIONS = (
    (0, '未融资'),
    (1, '天使轮'),
    (2, 'A轮'),
    (3, 'B轮'),
    (4, 'C轮'),
    (5, 'D轮及以上'),
    (6, '已上市'),
    (7, '不需要融资')
)

STAFF_SIZE_OPTIONS = (
    (0, '0-20人'),
    (1, '20-99人'),
    (2, '100-499人'),
    (3, '500-999人'),
    (4, '1000-9999人'),
    (5, '10000人以上')
)

OVERTIME_WORK_OPTIONS = (
    (0, '不加班'),
    (1, '偶尔加班'),
    (2, '弹性工作')
)

DAY_OFF_OPTIONS = (
    (0, '双休'),
    (1, '单休'),
    (2, '大小周'),
    (3, '排班轮休')
)

JOB_STATUS_OPTIONS = (
    (0, '离职-随时到岗'),
    (1, '在职-暂不考虑'),
    (2, '在职-考虑机会'),
    (3, '在职-月内到岗'),
)

JOB_TYPE_OPTIONS = (
    (0, '社招'),
    (1, '实习生'),
    (2, '应届校招'),
)

EDU_TYPE_OPTIONS = (
    (0, '无'),
    (1, '全日制'),
    (2, '非全日制')
)

DIPLOMA_OPTIONS = (
    (0, '不限'),
    (1, '初中及以下'),
    (2, '中专/中技'),
    (3, '高中'),
    (4, '大专'),
    (5, '本科'),
    (6, '硕士'),
    (7, '博士')
)


class BaseModel(models.Model):
    insert_time = models.DateTimeField(auto_now_add=True, verbose_name='创建日期')
    delete_time = models.DateTimeField(null=True, blank=True, verbose_name='删除日期')
    update_time = models.DateTimeField(null=True, blank=True, verbose_name='最后更新日期')
    is_deleted = models.BooleanField(default=False, blank=True, verbose_name='是否被删除')
    memo = models.CharField(max_length=8000, blank=True, default='', verbose_name='备注')

    def __str__(self):
        value = getattr(self, 'name', None)
        if not value:
            value = getattr(self, 'id', None)
        if not value:
            value = getattr(self, f'{str(self.__class__).lower()}name', None)
        if not value:
            value = getattr(self, f'{str(self.__class__).lower()}id', None)
        return str(value) or super().__str__()

    class Meta:
        abstract = True


class User(BaseModel):
    """用户"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    username = models.CharField(unique=True, max_length=20, verbose_name='用户名')
    password = models.CharField(max_length=64, verbose_name='密码')
    last_visit = models.DateTimeField(null=True, blank=True, verbose_name='登录日期')
    is_boss = models.BooleanField(default=False, verbose_name='是否Boss')
    is_locked = models.BooleanField(default=False, verbose_name='是否锁定')

    def save(self, insert=True, *args, **kwargs):
        if insert:
            self.password = make_sha256_digest(self.password)
        super().save(*args, **kwargs)

    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户'
        verbose_name_plural = '用户'


class LoginLog(BaseModel):
    """登录日志"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    user = models.ForeignKey(to=User, on_delete=models.DO_NOTHING,
                             db_constraint=False, verbose_name='用户')
    login_time = models.DateTimeField(auto_now_add=True, verbose_name='登录日期')
    device_code = models.CharField(max_length=50, default='', blank=True, verbose_name='设备编码')
    ip_address = models.CharField(max_length=20, default='', blank=True, verbose_name='IP地址')

    class Meta:
        db_table = 'tb_login_log'
        verbose_name = '登录日志'
        verbose_name_plural = '登录日志'


class District(models.Model):
    """行政单位"""
    id = models.IntegerField(primary_key=True, verbose_name='编号')
    parent = models.ForeignKey(to='self', on_delete=models.DO_NOTHING, db_constraint=False,
                               related_name='children', default=0, verbose_name='父级行政单位')
    name = models.CharField(max_length=255, verbose_name='行政单位名称')
    is_hot = models.BooleanField(default=False, verbose_name='是否热门城市')

    def __str__(self):
        return self.name

    def parent_info(self):
        return self.parent.name

    parent_info.short_description = '父级行政区域'

    class Meta:
        db_table = 'tb_district'
        verbose_name = '地区'
        verbose_name_plural = '地区'


class IndustryCategory(BaseModel):
    """行业类型"""
    id = models.AutoField(primary_key=True, verbose_name='行业类型编号')
    name = models.CharField(max_length=50, verbose_name='行业名称')
    parent = models.ForeignKey(to='self', on_delete=models.DO_NOTHING, db_constraint=False,
                               default=0, null=True, blank=True, verbose_name='父级行业')
    intro = models.CharField(max_length=2000, default='', verbose_name='行业介绍')

    class Meta:
        db_table = 'tb_industry_category'
        verbose_name = '行业'
        verbose_name_plural = '行业'


class PositionCategory(BaseModel):
    """职位类型"""
    id = models.AutoField(primary_key=True, verbose_name='职位类型编号')
    name = models.CharField(max_length=50, verbose_name='职位名称')
    parent = models.ForeignKey(to='self', on_delete=models.DO_NOTHING, db_constraint=False,
                               default=0, verbose_name='父级职位')
    is_hot = models.BooleanField(default=False, verbose_name='是否热门职位')

    class Meta:
        db_table = 'tb_position_category'
        verbose_name = '职位'
        verbose_name_plural = '职位'


class SkillTag(BaseModel):
    """技能标签"""
    id = models.AutoField(primary_key=True, verbose_name='技能标签编号')
    name = models.CharField(max_length=20, verbose_name='技能标签名称')
    position = models.ForeignKey(to=PositionCategory, on_delete=models.DO_NOTHING,
                                 db_constraint=False, verbose_name='所属职位')

    def position_info(self):
        return self.position.name

    position_info.short_description = '所属职位'

    class Meta:
        db_table = 'tb_skill_tag'
        verbose_name = '技能标签'
        verbose_name_plural = '技能标签'


class Company(BaseModel):
    """公司"""
    id = models.AutoField(primary_key=True, verbose_name='公司编号')
    logo = models.CharField(max_length=1024, verbose_name='公司Logo')
    short_name = models.CharField(max_length=10, verbose_name='公司简称')
    full_name = models.CharField(max_length=50, verbose_name='公司全称')
    industry_category = models.ForeignKey(to=IndustryCategory, on_delete=models.DO_NOTHING,
                                          db_constraint=False, verbose_name='所属行业')
    financing_stage = models.IntegerField(default=0, choices=FINANCING_STAGE_OPTIONS, verbose_name='融资阶段')
    staff_size = models.IntegerField(default=0, choices=STAFF_SIZE_OPTIONS, verbose_name='人员规模')
    web_site = models.CharField(max_length=1024, default='', verbose_name='公司网址')
    intro = models.CharField(max_length=10000, default='', verbose_name='公司介绍')
    start_work_time = models.CharField(max_length=10, default='', verbose_name='上班时间')
    end_work_time = models.CharField(max_length=10, default='', verbose_name='下班时间')
    overtime_work = models.IntegerField(default=0, choices=OVERTIME_WORK_OPTIONS, verbose_name='加班情况')
    day_off = models.IntegerField(default=0, choices=DAY_OFF_OPTIONS, verbose_name='休息时间')
    # 通过ManyToManyField字段的through属性指定维系多对多关系的中间实体
    welfares = models.ManyToManyField(to='Welfare', through='CompanyWelfare')
    editor = models.ForeignKey(to='User', on_delete=models.DO_NOTHING,
                               db_constraint=False, verbose_name='编辑者')

    def __str__(self):
        return self.short_name

    def industry_info(self):
        return self.industry_category.name

    industry_info.short_description = '所属行业'

    def editor_info(self):
        return self.editor.id

    editor_info.short_description = '编辑者'

    class Meta:
        db_table = 'tb_company'
        verbose_name = '公司'
        verbose_name_plural = '公司'


class CompanyDetail(models.Model):
    """工商信息"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    legal_representative = models.CharField(max_length=50, verbose_name='法人代表')
    registered_capital = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='注册资本')
    registered_capital_unit = models.CharField(max_length=10, verbose_name='注册资本单位')
    establishment_date = models.DateField(verbose_name='成立日期')
    company_type = models.CharField(max_length=50, verbose_name='公司类型')
    operating_state = models.CharField(max_length=10, verbose_name='经营状况')
    registered_place = models.CharField(max_length=256, verbose_name='注册地址')
    uni_credit_code = models.CharField(max_length=20, verbose_name='统一信用代码')
    # 通过OneToOneField可以表示一对一关系（它是多对一关系的特例）
    company = models.OneToOneField(to=Company, on_delete=models.DO_NOTHING,
                                   db_constraint=False, verbose_name='公司')

    def registered_capital_info(self):
        return f'{self.registered_capital}{self.registered_capital_unit}'

    registered_capital_info.short_description = '注册资本'

    class Meta:
        db_table = 'tb_company_detail'
        verbose_name = '工商信息'
        verbose_name_plural = '工商信息'


class Welfare(models.Model):
    """福利"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    logo = models.CharField(max_length=256, verbose_name='图标')
    name = models.CharField(max_length=10, verbose_name='福利名称')
    detail = models.CharField(max_length=50, verbose_name='福利详情')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tb_welfare'
        verbose_name = '福利'
        verbose_name_plural = '福利'


class CompanyWelfare(BaseModel):
    """公司福利（表示公司和福利之间多对多关系的中间实体）"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    company = models.ForeignKey(to=Company, on_delete=models.DO_NOTHING,
                                db_constraint=False, verbose_name='公司')
    welfare = models.ForeignKey(to=Welfare, on_delete=models.DO_NOTHING,
                                db_constraint=False, verbose_name='福利')
    editor = models.ForeignKey(to='User', on_delete=models.DO_NOTHING,
                               db_constraint=False, verbose_name='编辑者')

    class Meta:
        db_table = 'tb_company_welfare'
        verbose_name = '公司福利'
        verbose_name_plural = '公司福利'


class CompanyPhoto(BaseModel):
    """公司照片"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    photoname = models.ImageField(verbose_name='照片地址')
    company = models.ForeignKey(to=Company, on_delete=models.DO_NOTHING,
                                db_constraint=False, verbose_name='公司')
    editor = models.ForeignKey(to='User', on_delete=models.DO_NOTHING,
                               db_constraint=False, verbose_name='编辑者')

    class Meta:
        db_table = 'tb_company_photo'
        verbose_name = '公司照片'
        verbose_name_plural = '公司照片'


class Job(BaseModel):
    """招聘岗位"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    company = models.ForeignKey(to=Company, on_delete=models.DO_NOTHING,
                                db_constraint=False, verbose_name='公司')
    job_type = models.IntegerField(default=0, choices=JOB_TYPE_OPTIONS, verbose_name='招聘类型')
    job_name = models.CharField(max_length=20, verbose_name='职位名称')
    district = models.ForeignKey(to=District, on_delete=models.DO_NOTHING,
                                 db_constraint=False, verbose_name='工作城市')
    street_info = models.CharField(max_length=256, default='', verbose_name='工作地址')
    room_info = models.CharField(max_length=50, default='', blank=True, verbose_name='门牌号')
    latitude = models.DecimalField(null=True, blank=True, max_digits=10, decimal_places=6, verbose_name='纬度')
    longtitude = models.DecimalField(null=True, blank=True, max_digits=10, decimal_places=6, verbose_name='经度')
    min_work_year = models.IntegerField(default=0, verbose_name='最低工作年限')
    max_work_year = models.IntegerField(default=0, verbose_name='最高工作年限')
    min_diploma = models.IntegerField(default=0, choices=DIPLOMA_OPTIONS, verbose_name='最低学历')
    min_salary = models.IntegerField(default=1, verbose_name='最低薪资')
    max_salary = models.IntegerField(default=1, verbose_name='最高薪资')
    salary_month = models.IntegerField(default=12, verbose_name='计薪月数')
    detail = models.CharField(max_length=5000, verbose_name='职位描述')
    user = models.ForeignKey(to=User, on_delete=models.DO_NOTHING,
                             db_constraint=False, verbose_name='职位发布者')
    pub_date = models.DateTimeField(auto_now=True, verbose_name='发布时间日期')
    is_open = models.BooleanField(default=True, verbose_name='是否开放')

    def company_info(self):
        return self.company.short_name

    company_info.short_description = '公司简称'

    def district_info(self):
        return self.district.name

    district_info.short_description = '工作城市'

    def work_years(self):
        if self.min_work_year > 0:
            return f'{self.min_work_year}-{self.max_work_year}年'
        else:
            return '不限'

    work_years.short_description = '工作年限'

    def salary_info(self):
        return f'{self.min_salary}K-{self.max_salary}K {self.salary_month}薪'

    salary_info.short_description = '月薪'

    def user_info(self):
        info = BasicInfo.objects.filter(user__id=self.user.id).first()
        return f'{info.realname[:1]}{"先生" if info.sex else "女士"}' if info else ''

    user_info.short_description = '招聘者'

    class Meta:
        db_table = 'tb_job'
        verbose_name = '招聘岗位'
        verbose_name_plural = '招聘岗位'


class BasicInfo(BaseModel):
    """基本信息"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    realname = models.CharField(max_length=50, verbose_name='姓名')
    sex = models.BooleanField(default=True, verbose_name='性别')
    birth = models.DateField(verbose_name='生日')
    tel = models.CharField(max_length=50, verbose_name='电话')
    status = models.IntegerField(choices=JOB_STATUS_OPTIONS, default=0, verbose_name='求职状态')
    wechat = models.CharField(max_length=50, default='', verbose_name='微信号')
    email = models.CharField(max_length=254, default='', verbose_name='邮箱')
    intro = models.CharField(max_length=140, verbose_name='个人优势')
    user = models.OneToOneField(to=User, on_delete=models.DO_NOTHING,
                                db_constraint=False, verbose_name='用户')

    class Meta:
        db_table = 'tb_basic_info'
        verbose_name = '基本信息'
        verbose_name_plural = '基本信息'


class DesiredPosition(BaseModel):
    """期望职位"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    position_category = models.ForeignKey(to=PositionCategory, on_delete=models.DO_NOTHING,
                                          db_constraint=False, verbose_name='职位类型')
    user = models.ForeignKey(to=User, on_delete=models.DO_NOTHING,
                             db_constraint=False, verbose_name='用户')
    min_salary = models.IntegerField(default=0, verbose_name='月薪下限')
    max_salary = models.IntegerField(default=99999999, verbose_name='月薪上限')
    industries = models.CharField(max_length=100, verbose_name='行业')
    district = models.ForeignKey(to=District, on_delete=models.DO_NOTHING,
                                 db_constraint=False, verbose_name='城市')

    def position_info(self):
        return self.position_category.name

    position_info.short_description = '期望职位'

    def user_info(self):
        return f'{self.user.id}:{self.user.username}'

    user_info.description = '用户'

    def district_info(self):
        return self.district.name

    district_info.short_description = '城市'

    class Meta:
        db_table = 'tb_desired_position'
        verbose_name = '期望职位'
        verbose_name_plural = '期望职位'


class JobExperience(BaseModel):
    """工作经历"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    company_name = models.CharField(max_length=50, verbose_name='公司名称')
    industry_category = models.ForeignKey(to=IndustryCategory, on_delete=models.DO_NOTHING,
                                          db_constraint=False, verbose_name='所属行业')
    department_name = models.CharField(max_length=50, verbose_name='所属部门')
    position_name = models.CharField(max_length=50, verbose_name='职位名称')
    position_category = models.ForeignKey(to=PositionCategory, on_delete=models.DO_NOTHING,
                                          db_constraint=False, verbose_name='职位类型')
    start_date = models.DateField(verbose_name='开始日期')
    end_date = models.DateField(null=True, verbose_name='结束日期')
    skill_tags = models.CharField(max_length=1000, verbose_name='技能标签')
    detail = models.CharField(max_length=1600, verbose_name='工作内容')
    achievement = models.CharField(max_length=300, verbose_name='工作业绩')
    hide_option = models.BooleanField(default=True, verbose_name='是否对当前公司隐藏')
    company = models.ForeignKey(to=Company, on_delete=models.DO_NOTHING,
                                db_constraint=False, verbose_name='公司')
    user = models.ForeignKey(to=User, on_delete=models.DO_NOTHING,
                             db_constraint=False, verbose_name='用户')
    is_current = models.BooleanField(default=False, verbose_name='是否当前工作')

    def industry_info(self):
        return self.industry_category.name

    industry_info.short_description = '所属行业'

    def position_info(self):
        return self.position_category.name

    position_info.short_description = '职位类型'

    def company_info(self):
        return f'{self.company.id}:{self.company.short_name}'

    company_info.short_description = '公司信息'

    def user_info(self):
        return f'{self.user.id}:{self.user.username}'

    user_info.description = '用户'

    class Meta:
        db_table = 'tb_job_experience'
        verbose_name = '工作经历'
        verbose_name_plural = '工作经历'


class ProjectExperience(BaseModel):
    """项目经历"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    project_name = models.CharField(max_length=50, verbose_name='项目名称')
    project_role = models.CharField(max_length=50, verbose_name='项目角色')
    project_url = models.CharField(max_length=1024, default='', blank=True, verbose_name='项目链接')
    start_date = models.DateField(verbose_name='开始日期')
    end_date = models.DateField(verbose_name='结束日期')
    detail = models.CharField(max_length=1600, verbose_name='项目描述')
    achievements = models.CharField(max_length=300, verbose_name='项目业绩')
    user = models.ForeignKey(to=User, on_delete=models.DO_NOTHING,
                             db_constraint=False, verbose_name='用户')

    def user_info(self):
        return f'{self.user.id}:{self.user.username}'

    user_info.description = '用户'

    class Meta:
        db_table = 'tb_project_experience'
        verbose_name = '项目经历'
        verbose_name_plural = '项目经历'


class EducationExperience(BaseModel):
    """教育经历"""
    id = models.AutoField(primary_key=True, verbose_name='b编号')
    school_name = models.CharField(max_length=50, verbose_name='学校名称')
    education_type = models.IntegerField(default=0, choices=EDU_TYPE_OPTIONS, verbose_name='类型')
    diploma = models.IntegerField(default=5, choices=DIPLOMA_OPTIONS, verbose_name='学历')
    major = models.CharField(max_length=50, verbose_name='专业')
    start_year = models.CharField(max_length=10, verbose_name='开始时间')
    end_year = models.CharField(max_length=10, verbose_name='结束时间')
    detail = models.CharField(max_length=300, verbose_name='在校经历')
    user = models.ForeignKey(to=User, on_delete=models.DO_NOTHING,
                             db_constraint=False, verbose_name='用户')

    def user_info(self):
        return f'{self.user.id}:{self.user.username}'

    user_info.description = '用户'

    class Meta:
        db_table = 'tb_education_experience'
        verbose_name = '教育经历'
        verbose_name_plural = '教育经历'


class Attachment(BaseModel):
    """附件"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    name = models.CharField(max_length=100, verbose_name='文件名')
    path = models.FileField(max_length=1024, verbose_name='文件路径')
    user = models.ForeignKey(to=User, on_delete=models.DO_NOTHING,
                             db_constraint=False, verbose_name='用户')

    def user_info(self):
        return f'{self.user.id}:{self.user.username}'

    user_info.description = '用户'

    class Meta:
        db_table = 'tb_attachment'
        verbose_name = '附件'
        verbose_name_plural = '附件'


class Message(BaseModel):
    """站内消息"""
    id = models.AutoField(primary_key=True, verbose_name='编号')
    from_user = models.ForeignKey(to=User, related_name='+', on_delete=models.DO_NOTHING,
                                  db_constraint=False, verbose_name='发送者')
    to_user = models.ForeignKey(to=User, related_name='+', on_delete=models.DO_NOTHING,
                                db_constraint=False, verbose_name='接收者')
    content = models.CharField(max_length=1000, verbose_name='内容')

    def from_user_info(self):
        return f'{self.from_user.id}:{self.from_user.username}'

    from_user_info.description = '用户'

    def to_user_info(self):
        return f'{self.to_user.id}:{self.to_user.username}'

    to_user_info.description = '用户'

    class Meta:
        db_table = 'tb_message'
        verbose_name = '站内消息'
        verbose_name_plural = '站内消息'
